package com.my.zl.console.service.autocode.impl;

import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.my.zl.common.dto.ReqDTO;
import com.my.zl.common.dto.advancedQuery.PageQueryDTO;
import com.my.zl.common.enums.resp.GlobalEnum;
import com.my.zl.common.exception.BizException;
import com.my.zl.common.utils.CopyUtil;
import com.my.zl.console.common.constant.AutocodeC;
import com.my.zl.console.common.constant.AutocodeRespE;
import com.my.zl.console.dao.autocode.ZlTableColumnMapper;
import com.my.zl.console.dao.autocode.ZlTableMapper;
import com.my.zl.console.dto.autocode.table.ReqTableAddDTO;
import com.my.zl.console.dto.autocode.table.ReqTableDelDTO;
import com.my.zl.console.dto.autocode.table.ReqTableDetailDTO;
import com.my.zl.console.dto.autocode.table.ReqTableEditDTO;
import com.my.zl.console.dto.autocode.table.ReqTableQueryDTO;
import com.my.zl.console.dto.autocode.table.ReqTableStateDTO;
import com.my.zl.console.dto.autocode.table.ResTableAddDTO;
import com.my.zl.console.dto.autocode.table.ResTableDelDTO;
import com.my.zl.console.dto.autocode.table.ResTableDetailDTO;
import com.my.zl.console.dto.autocode.table.ResTableEditDTO;
import com.my.zl.console.dto.autocode.table.ResTableQueryDTO;
import com.my.zl.console.dto.autocode.table.ResTableStateDTO;
import com.my.zl.console.dto.autocode.table.ResTableVO2;
import com.my.zl.console.entity.autocode.ZlTable;
import com.my.zl.console.entity.autocode.ZlTableColumn;
import com.my.zl.console.po.autocode.table.ZlTableVo;
import com.my.zl.console.po.autocode.tableColumn.ZlTableColumnVo;
import com.my.zl.console.service.autocode.ITableService;
import com.my.zl.console.service.base.BaseManager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;

/**
 * 数据库表信息
 * @author ZL
 */
@Service
public class TableServiceImpl extends BaseManager implements ITableService {

    @Autowired
    private ZlTableMapper tableMapper;
    @Autowired
    private ZlTableColumnMapper tableColumnMapper;

    @Override
    public ResTableQueryDTO queryTableList(ReqTableQueryDTO reqInfo,PageQueryDTO page) throws Exception{
        // TODO Auto-generated method stub
        ResTableQueryDTO resDTO = BeanUtil.copyProperties(page, ResTableQueryDTO.class);
        if(StringUtils.isNotBlank(reqInfo.getTableCode())){
            reqInfo.setTableCode("%"+reqInfo.getTableCode()+"%");
        }
        if(StringUtils.isNotBlank(reqInfo.getTableName())){
            reqInfo.setTableName("%"+reqInfo.getTableName()+"%");
        }
        if(StringUtils.isNotBlank(reqInfo.getTableTag())){
            reqInfo.setTableTag("%"+reqInfo.getTableTag()+"%");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqInfo);
        
        pageHandle(page);//处理分页数据
        //当效率不行时自行计数，或完全自行分页，先查询总数，如果为0不用再次查询了；开启计数：true是,false否
        //临近第一条SQL查询语句自动分页,如果未消费时(即后面没有触发SQL查询)则需主动调用pageHp.clear()清理
        Page<Object> pageHp = PageHelper.startPage(page.getPage(), page.getLimit(),page.getSortorder());
        List<ZlTableVo> list = tableMapper.selectListPage(paramMap);
        resDTO.setData(CopyUtil.copyList(list, ResTableVO2.class));
        resDTO.setCount(pageHp.getTotal());
        
        return resDTO;
    }
    
    @Override
    public ResTableDetailDTO queryTableDetail(ReqTableDetailDTO reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ResTableDetailDTO res = new ResTableDetailDTO();
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqInfo);
        ZlTable view = tableMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(view, res);
        return res;
    }
    
    @Override
    public ResTableAddDTO insertTableInfo(ReqDTO<ReqTableAddDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTableAddDTO reqData = reqInfo.getReqData();
        ResTableAddDTO res = new ResTableAddDTO();
        Instant time = getSystemTime().getUtcTime();
        
        ZlTable record = new ZlTable();
        BeanUtil.copyProperties(reqData, record);
        
        initCreateInfo(record, reqInfo, time);
        record.setTableId(IdUtil.simpleUUID());
        record.setDataStatus(AutocodeC.DataStatus.ENABLE.getCode());//状态
        
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("tableId",record.getTableId());
        //检查主键是否冲突
        if(tableMapper.countExistKey(paramMap)>0){
            throw new BizException(GlobalEnum.DUPLICATE_PRIMARY_KEY);
        }
        
        tableMapper.insertSelective(record);
        
        ZlTable keyInfo = tableMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTableEditDTO updateTableInfo(ReqDTO<ReqTableEditDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTableEditDTO reqData = reqInfo.getReqData();
        ResTableEditDTO res = new ResTableEditDTO();
        Instant time = getSystemTime().getUtcTime();
        
        ZlTable record = new ZlTable();
        BeanUtil.copyProperties(reqData, record);
        
        initUpdateInfo(record, reqInfo, time);
        
        tableMapper.updateByPrimaryKeySelective(record);
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("tableId",record.getTableId());
        ZlTable keyInfo = tableMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTableDelDTO deleteTableInfo(ReqDTO<ReqTableDelDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTableDelDTO reqData = reqInfo.getReqData();
        ResTableDelDTO res = new ResTableDelDTO();
        Instant time = getSystemTime().getUtcTime();
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("tableId",reqData.getTableId());
        ZlTable record = tableMapper.selectOneByMap(paramMap);
        paramMap.put("tableCode",record.getTableCode());
        if(tableColumnMapper.countExistKey(paramMap) > 0){
            throw new BizException(AutocodeRespE.DELETE_NOT_ALLOWED);
        }
        
        paramMap = BeanUtil.beanToMap(reqData);
        tableMapper.deleteByMap(paramMap);
        
        return res;
    }
    
    @Override
    public ResTableStateDTO updateTableState(ReqDTO<ReqTableStateDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTableStateDTO reqData = reqInfo.getReqData();
        ResTableStateDTO res = new ResTableStateDTO();
        Instant time = getSystemTime().getUtcTime();
         
        ZlTable record = new ZlTable();
        BeanUtil.copyProperties(reqData, record);
        initUpdateInfo(record, reqInfo, time);
        tableMapper.updateByPrimaryKeySelective(record);
         
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("tableId",record.getTableId());
        ZlTable keyInfo = tableMapper.selectOneByMap(paramMap);
        BeanUtil.copyProperties(keyInfo, res);
        
        return res;
    }
    
    @Override
    public ResTableQueryDTO queryTableColumnList(ReqTableQueryDTO reqInfo,PageQueryDTO page) throws Exception{
        // TODO Auto-generated method stub
        ResTableQueryDTO resDTO = BeanUtil.copyProperties(page, ResTableQueryDTO.class);
        
        if(StringUtils.isNotBlank(reqInfo.getTableCode())){
            reqInfo.setTableCode("%"+reqInfo.getTableCode()+"%");
        }
        if(StringUtils.isNotBlank(reqInfo.getTableName())){
            reqInfo.setTableName("%"+reqInfo.getTableName()+"%");
        }
        if(StringUtils.isNotBlank(reqInfo.getTableTag())){
            reqInfo.setTableTag("%"+reqInfo.getTableTag()+"%");
        }
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap = BeanUtil.beanToMap(reqInfo);
        
        pageHandle(page);//处理分页数据
        //当效率不行时自行计数，或完全自行分页，先查询总数，如果为0不用再次查询了；开启计数：true是,false否
        //临近第一条SQL查询语句自动分页,如果未消费时(即后面没有触发SQL查询)则需主动调用pageHp.clear()清理
        Page<Object> pageHp = PageHelper.startPage(page.getPage(), page.getLimit(),page.getSortorder());
        List<ZlTableVo> list = tableMapper.selectListPage(paramMap);
        for(ZlTableVo lt: list){
            Map<String, Object> paramMap2 = new HashMap<>();
            paramMap2.put("tableCode", lt.getTableCode());
            paramMap2.put("projectId", lt.getProjectId());
            List<ZlTableColumn> columnList = tableColumnMapper.selectListByMapForSelectItem(paramMap2);
            List<ZlTableColumnVo> columnInfos = new ArrayList<>();
            if(columnList != null && columnList.size()>0){
                for(ZlTableColumn colx: columnList){
                    columnInfos.add(BeanUtil.copyProperties(colx, ZlTableColumnVo.class));
                }
                lt.setColumnInfos(columnInfos);
            }
        }
        resDTO.setData(CopyUtil.copyList(list, ResTableVO2.class));
        resDTO.setCount(pageHp.getTotal());
        
        return resDTO;
    }
    
    @Override
    public ResTableDelDTO deleteTableAndColumn(ReqDTO<ReqTableDelDTO> reqInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqTableDelDTO reqData = reqInfo.getReqData();
        ResTableDelDTO res = new ResTableDelDTO();
        Instant time = getSystemTime().getUtcTime();
        
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("tableId",reqData.getTableId());
        ZlTable record = tableMapper.selectOneByMap(paramMap);
        paramMap = BeanUtil.beanToMap(reqData);
        paramMap.put("tableCode",record.getTableCode());
        
        tableMapper.deleteByMap(paramMap);
        tableColumnMapper.deleteByMap(paramMap);
        
        return res;
    }
}